package qqserver.service;

import qqcommon.Message;
import qqcommon.MessageType;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

/**
 * @author DCSGO
 * @version 1.0
 * 该类用于向客户端 发送/接收消息
 * 并进行响应即执行相关操作
 */
public class ServerConnectClientThread extends Thread {
    private final String userId;
    private final Socket clientSocket;

    @Override
    public void run() {
        try {
            while (true) {
                //读取客户端发送的消息
                ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
                Message message = (Message) ois.readObject();

                if (message.getMesType().equals(MessageType.MESSAGE_GET_ONLINE_USERS)) {
                    //回传所有在线用户名
                    System.out.println(message.getSender() + " 请求拉取在线用户信息！");
                    //1.消息类型设置为 返回所有在线用户信息消息
                    Message resMessage = new Message();
                    resMessage.setMesType(MessageType.MESSAGE_RET_ONLINE_USERS);
                    //2.消息内容设置为 所有在线用户名 用户名之间用空格分隔
                    resMessage.setContent(ManageServerConnectClientThreads.getAllUsers());
                    //3.发送该消息
                    ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
                    oos.writeObject(resMessage);
                } else if (message.getMesType().equals(MessageType.MESSAGE_CLIENT_EXIT)) {
                    //客户端下线
                    System.out.println(message.getSender() + " 请求下线！");
                    //关闭相关资源
                    clientSocket.close();
                    ManageServerConnectClientThreads.remove(message.getSender());
                    SendMessageToOfflineService.addOfflineUser(message.getSender());
                    break;//结束该线程
                } else if (message.getMesType().equals(MessageType.MESSAGE_COMM_MES)) {
                    //找到接收线程
                    ServerConnectClientThread clientThread = ManageServerConnectClientThreads.get(message.getReceiver());
                    if (clientThread != null) {//该用户在线
                        System.out.println(message.getSender() + " 向 " + message.getReceiver() + " 发送消息！");
                        //将该 message 转发给 指定用户
                        ObjectOutputStream oos = new ObjectOutputStream(clientThread.getClientSocket().getOutputStream());
                        oos.writeObject(message);
                    } else {//该用户不存在或已下线
                        if (SendMessageToOfflineService.isOfflineUser(message.getReceiver())) {
                            //该用户离线 将该消息保存
                            SendMessageToOfflineService.addMessage(message);
                        } else {
                            //该用户不存在 向发送的用户回复 该用户不存在！
                            message.setMesType(MessageType.MESSAGE_FAIL_IN_SEND);
                            message.setContent("该用户不存在！");
                            ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
                            oos.writeObject(message);
                        }
                    }

                } else if (message.getMesType().equals(MessageType.MESSAGE_TO_ALL_MES)) {
                    //广播该消息
                    System.out.println(message.getSender() + " 请求向所有在线用户发送消息！");
                    ArrayList<Socket> otherClientSockets = ManageServerConnectClientThreads.getOtherClientSockets(message.getSender());
                    if (otherClientSockets != null) {//有其他在线用户
                        for (Socket clientSocket : otherClientSockets) {
                            ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
                            oos.writeObject(message);
                        }
                    } else {//在线用户只有发送者自己
                        //向发送的用户回复 发送失败
                        message.setMesType(MessageType.MESSAGE_FAIL_IN_SEND);
                        message.setContent("在线用户只有你自己！");
                        ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
                        oos.writeObject(message);
                    }
                } else if (message.getMesType().equals(MessageType.MESSAGE_FILE_MES)) {
                    //找到接收线程
                    ServerConnectClientThread clientThread = ManageServerConnectClientThreads.get(message.getReceiver());
                    if (clientThread != null) {//该用户在线
                        System.out.println(message.getSender() + " 向 " + message.getReceiver() + " 发送文件！");
                        Socket receiverSocket = clientThread.getClientSocket();
                        ObjectOutputStream oos = new ObjectOutputStream(receiverSocket.getOutputStream());
                        oos.writeObject(message);
                    } else {
                        //向发送的用户回复 发送失败
                        if (SendMessageToOfflineService.isOfflineUser(message.getReceiver())) {
                            //接收用户离线
                            SendMessageToOfflineService.addMessage(message);
                        } else {
                            message.setMesType(MessageType.MESSAGE_FAIL_IN_SEND);
                            message.setFileBytes(null);
                            message.setFileLen(-1);
                            message.setContent("该用户不存在！");
                            ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
                            oos.writeObject(message);
                        }
                    }
                } else {
                    System.out.println("其他消息类型，暂未处理...");
                }


            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    public ServerConnectClientThread(String userId, Socket clientSocket) {
        this.userId = userId;
        this.clientSocket = clientSocket;
    }

    public String getUserId() {
        return userId;
    }

    public Socket getClientSocket() {
        return clientSocket;
    }
}
